'''
Created on Dec 20, 2010

@author: dexen
'''

from dexen.system.common.base import Action
from dexen.system.server.archive_mgr import ArchiveMgr
from dexen.system.common.transact import Transaction, MasterRecvTransact


class ActionMgr(object):
    def __init__(self, job_meta):
        self.actions = []
        self.archive_mgr = ArchiveMgr(job_meta)
    
    def _archive_inds(self, inds):
        self.archive_mgr.archive_inds(inds)
        
    def _process(self, actions):
        for action in actions:
            assert isinstance(action, Action)
            transact = action.get_transact()
            assert isinstance(transact, Transaction)
            inds = transact.get_inds()
            self._archive_inds(inds)
            transact.set_inds(inds) # Needed to replace inds back with stripped archive version
            if isinstance(transact, MasterRecvTransact):
                assert isinstance(transact, MasterRecvTransact)
                self.archive_mgr.archive_master(transact.get_archive())
                transact.strip_archive()
            
    def add_actions(self, actions):
        self.actions.extend(actions)
        self._process(actions)

    def get_actions(self, act_id):
        #act_id refers to the last id that the client has received
        acts = []
        for i, action in enumerate(self.actions[act_id:]):
            assert isinstance(action, Action)
            assert action.get_id() == act_id + i+1 #act_id starts from 1, list index starts from 0
            acts.append(action)
        return acts
    
    def on_delete(self):
        self.archive_mgr.delete_all()
        
        
